Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | "use client"; import { useState, useEffect } from "react"; import { useRouter, useParams } from "next/navigation"; import dynamic from "next/dynamic"; import { ProductFormSkeleton } from "@/components/ui/Skeleton"; const ProductForm = dynamic( () => import("@/components/features/admin/ProductForm").then((mod) => ({ default: mod.ProductForm })), { loading: () => <ProductFormSkeleton />, ssr: false, // Admin doesn't need SSR } ); export default function EditProductPage() { const router = useRouter(); const params = useParams(); const productId = parseInt(params.id as string); const [product, setProduct] = useState(null); const [categories, setCategories] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); useEffect(() => { const fetchData = async () => { try { const [productRes, categoriesRes] = await Promise.all([ fetch(`/api/admin/products/${productId}`), fetch("/api/admin/categories"), ]); if (!productRes.ok) throw new Error("Product not found"); const productData = await productRes.json(); const categoriesData = await categoriesRes.json(); setProduct(productData.data || productData); if (categoriesData.success) { setCategories(categoriesData.data); } } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred'); } finally { setLoading(false); } }; fetchData(); }, [productId]); const handleSubmit = async (data: { title: string; description: string; price: string | number; discountedPrice: string | number; stock: number; categoryId: string | number; sku: string; images?: Array<{ id: number; url: string; thumbnailUrl: string; order: number }>; }) => { const response = await fetch(`/api/admin/products/${productId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data)}); if (!response.ok) { const error = await response.json(); throw new Error(error.error || "Failed to update product"); } router.push("/admin/products"); }; if (loading) return <div style={{ padding: "20px" }}>Loading...</div>; if (error) return <div style={{ padding: "20px", color: "red" }}>Error: {error}</div>; return ( <div style={{ padding: "30px 0" }}> <div style={{ maxWidth: "900px", margin: "0 auto", paddingLeft: "30px", paddingRight: "30px" }}> <h1 style={{ marginBottom: "30px" }}>Edit Product</h1> {product && ( <ProductForm productId={productId} initialData={product} categories={categories} onSubmit={handleSubmit} /> )} </div> </div> ); } |